package hook

import (
	"encoding/json"
	"gitee.com/zhanghuamingmyself/hook/bean"
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
	"time"
)

type name struct {
}

var URL = "iot.mq.rabbit.ztn-tech.com"
var PORT = "5672"
var USER_NAME = "test"
var Password = "Ztn654321"
var EXCHANGE_NAME = "ztn.iot.sdk"
var QUEUE_BASE_NAME = EXCHANGE_NAME+"."
var IS_DURABLE = true

func Listen(topic string, receiver func(systemHookWarp bean.SystemHookWarp, err error)) {
	for true {
		doLister(topic, receiver)
		time.Sleep(4 * time.Second)
	}
}

func doLister(topic string, receiver func(systemHookWarp bean.SystemHookWarp, err error)) {
	queueName := QUEUE_BASE_NAME + topic
	conn, err := amqp.Dial("amqp://" + USER_NAME + ":" + Password + "@" + URL + ":" + PORT + "/")
	if err != nil {
		log.Println(err)
		return
	}
	defer conn.Close()
	notifyConnClose := make(chan *amqp.Error)
	conn.NotifyClose(notifyConnClose)
	channel, err := conn.Channel()
	if err != nil {
		log.Println(err)
		return
	}
	defer channel.Close()
	channel.ExchangeDeclare(EXCHANGE_NAME, "topic", true, false, false, true, nil)
	channel.QueueDeclare(queueName, IS_DURABLE, !IS_DURABLE, false, true, nil)
	channel.QueueBind(queueName, topic, EXCHANGE_NAME, true, nil)

	msgList, err := channel.Consume(queueName, "", true, false, false, false, nil)
	if err != nil {
		log.Printf("获取消费通道异常:%s \n", err)
		return
	}

	select {
	case msg := <-msgList:
		s := bean.SystemHookWarp{}
		err := json.Unmarshal(msg.Body, &s)
		if err != nil {
			log.Println(err)
		} else {
			receiver(s, nil)
		}
	case err := <-notifyConnClose:
		log.Println(err)
		return
	}
}
